package game.module.nn.processor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.RoomServer;
import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.nn.NnConstants;
import game.module.nn.bean.NnRound;
import game.module.nn.logic.NnDataManager;
import game.module.nn.logic.NnLogic;
import game.session.SessionManager;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageLogin.S2ErrorCode;
import lua.LuaMessageNn.C2SNnPeiPai;
import lua.LuaMessageNn.PushNnPeiPai;
import lua.LuaMessageNn.S2CNnPeiPai;

@MsgCodeAnn(msgcode = C2SNnPeiPai.id, accessLimit = 500)
public class NnPeiPaiProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(NnPeiPaiProcessor.class);

	@Override
	public void process(PlayingRole playingRole, RequestMessageRaw request) throws Exception {
		C2SNnPeiPai reqMsg = C2SNnPeiPai.parse(request);
		byte[] niu_10_cards = reqMsg.niu_10_cards;
		int playerId = playingRole.getId();
		logger.info("nn pei pai,playerId={},niu_10_cards={}", playerId, niu_10_cards);
		// 房间是否存在
		final NnRound ddzRound = NnDataManager.getInstance().getNnRoom(playerId);
		if (ddzRound == null) {
			S2ErrorCode retMsg = new S2ErrorCode(201);
			playingRole.writeAndFlush(retMsg.build(playingRole.alloc()));
			return;
		}
		// 是否已经存在
		Map<Integer, byte[]> peiPaiFinishPlayers = ddzRound.getPeiPaiFinish();
		if (peiPaiFinishPlayers != null && peiPaiFinishPlayers.containsKey(playerId)) {
			S2ErrorCode retMsg = new S2ErrorCode(308);
			playingRole.writeAndFlush(retMsg.build(playingRole.alloc()));
			return;
		}
		// 牌数量够不够
		int myIndex = ddzRound.getPlayerIds().indexOf(playerId);
		List<Byte> myCards = ddzRound.getCards().get(myIndex);
		if (myCards == null || myCards.size() != NnConstants.MAX_COUNT) {
			S2ErrorCode retMsg = new S2ErrorCode(309);
			playingRole.writeAndFlush(retMsg.build(playingRole.alloc()));
			return;
		}
		// do
		if (peiPaiFinishPlayers == null) {
			peiPaiFinishPlayers = new HashMap<>();
			ddzRound.setPeiPaiFinish(peiPaiFinishPlayers);
		}
		peiPaiFinishPlayers.put(playerId, niu_10_cards);
		// ret
		S2CNnPeiPai respMsg = new S2CNnPeiPai();
		playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
		// push
		List<Integer> playerIds = ddzRound.getPlayerIds();
		PushNnPeiPai pushMsg = new PushNnPeiPai((byte) myIndex);
		for (Integer aPlayerId : playerIds) {
			// 推送
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushMsg.build(pr.alloc()));
			}
		}
		// 牛牛结算
		if (peiPaiFinishPlayers.size() >= playerIds.size()) {
			NnLogic.getInstance().claculateResult(ddzRound);
			if (ddzRound.getRoundCount() < ddzRound.getRoundSum()) {
				RoomServer.executorService.schedule(new Runnable() {
					@Override
					public void run() {
						NnLogic.getInstance().nextRound(ddzRound);
					}
				}, 3, TimeUnit.SECONDS);
			} else {
				// TODO 最终结算
				NnLogic.getInstance().roundOver(ddzRound);
//				for (Integer aPlayerId : playerIds) {
//					NnDataManager.getInstance().removePlayer(aPlayerId);
//				}
//				ddzRound.setCards(null);
//				ddzRound.setPlayerIds(null);
//				ddzRound.setLoopCount(0);
//				ddzRound.setLastJiaoScore(null);
//				ddzRound.setZhuangJiaIndex(null);
//				ddzRound.getQiangZhuangJiaInfoList().clear();
//				ddzRound.getXianJiaXiaZhu().clear();
//				ddzRound.getPeiPaiFinish().clear();
			}
		}
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

}
